package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

import java.text.SimpleDateFormat;

/**
 * Author: Felix
 * Date: 2022/3/16
 * Desc: 独立访客计算
 * 需要启动启动的进程
 *      zk、kafka、logger、BaseLogApp、UniqueVisitorApp
 * 执行流程
 *      模拟生成日志数据
 *      将生成的日志数据发送给nginx
 *      nginx对日志数据进行负载均衡，将数据转发到三台日志采集服务器上
 *      日志采集服务器对日志数据进行处理，将日志发送到kafka的ods_base_log
 *      BaseLogApp从ods_base_log主题中读取数据进行分流
 *      UniqueVisitorApp从dwd_page_log中读取数据  ，对pv进行过滤，得到uv
 *      将uv数据写到kafka的dwm_unique_visitor主题中
 */
public class UniqueVisitorApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        //TODO 2.检查点相关的设置(略)
        //TODO 3.从kafka中读取数据
        //3.1 声明主题以及消费者组
        String topic = "dwd_page_log";
        String groupId = "unique_visitor_group";
        //3.2 创建消费者对象
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据  封装为流
        DataStreamSource<String> kafkaStrDS = env.addSource(kafkaSource);

        //TODO 4.对读取到的数据进行类型转换  jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.map(JSON::parseObject);

        //jsonObjDS.print(">>>>");

        //TODO 5.过滤
        //5.1 按照mid进行分组
        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));
        //5.2 使用Flink的状态编程对 pv数据进行过滤==>UV
        SingleOutputStreamOperator<JSONObject> filterDS = keyedDS.filter(
            new RichFilterFunction<JSONObject>() {
                private ValueState<String> lastVisitDateState;
                private SimpleDateFormat sdf;

                @Override
                public void open(Configuration parameters) throws Exception {
                    sdf = new SimpleDateFormat("yyyyMMdd");
                    ValueStateDescriptor valueStateDescriptor = new ValueStateDescriptor<String>("lastVisitDateState", String.class);
                    //因为是统计的日活，所以状态只需要保留一天即可
                    valueStateDescriptor.enableTimeToLive(
                        StateTtlConfig.newBuilder(Time.days(1))
                            //.setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                            //.setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                            .build()
                    );
                    lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                }

                @Override
                public boolean filter(JSONObject jsonObj) throws Exception {
                    String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                    if (lastPageId != null && lastPageId.length() > 0) {
                        //如果不为空，说明是从其他页面跳转过来的，直接将这条数据过滤掉
                        return false;
                    }

                    //利用状态进行过滤
                    String lastVisitDate = lastVisitDateState.value();
                    String curVisitDate = sdf.format(jsonObj.getLong("ts"));

                    if (lastVisitDate != null && lastVisitDate.length() > 0 && lastVisitDate.equals(curVisitDate)) {
                        //说明已经访问过
                        return false;
                    } else {
                        //说明还没有访问过，将这次访问的日期放到状态中
                        lastVisitDateState.update(curVisitDate);
                        return true;
                    }
                }
            }
        );

        filterDS.print(">>>>");
        //TODO 6.将过滤的结果写到kafka的主题中
        filterDS
            .map(jsonObj->jsonObj.toJSONString())
            .addSink(MyKafkaUtil.getKafkaSink("dwm_unique_visitor"));

        env.execute();

    }
}
